#include <WiFiClientSecure.h>
#include "wifi_mqtt_task.h"
#include "typedefine.h"
#include "certs.h"
#include "json_api.h"

// 函数声明
void wifi_mqtt_init(void);
void checkAndConnect(void);
void mqttCallback(char* topic, byte* payload, unsigned int length);
void controlCallback(char* topic, byte* payload, unsigned int length);
void registerTopics();
void publishMessage(const char* topic, const char* message);
void publishDeviceStatus(bool online, float voltage);

// MQTT配置
const char* mqtt_server = "192.168.28.16"; // MQTT服务器地址
const int mqtt_port = 8883;                   // SSL端口
const char* mqtt_user = "liadmin";           // MQTT用户名
const char* mqtt_pass = "123456";           // MQTT密码

// 全局定义主题配置数组
MQTT_Topic_Config topic_configs[] = {
    {"/date/" DEVICE_ID, nullptr},          // 发布主题
    {"/control/" DEVICE_ID, controlCallback}, // 订阅主题
};

WiFiClientSecure wifiClient;
PubSubClient mqttClient(wifiClient);

extern esp32_sta_t sta;
// WIFI配置
const char *ssid = "ReadmiK60";
const char *password = "07210d00";
const String deviceId = "ESP32_001";
static uint8_t retry_count = 0;

void wifi_mqtt_task(void *pvParameters) {
    wifi_mqtt_init();
    
    while (1) {
        checkAndConnect();
        mqttClient.loop(); // 维持MQTT

        publishDeviceStatus(true, 3.3f);

        vTaskDelay(10);
    }
}

void wifi_mqtt_init(void) {
    // WiFi初始化
    WiFi.disconnect(false);
    WiFi.setAutoConnect(true);
    WiFi.begin(ssid, password);

    // MQTT初始化
    // wifiClient.setCACert(CA_CERT);  // 设置CA证书
    wifiClient.setInsecure();    // 如果不验证证书（测试用）
    mqttClient.setServer(mqtt_server, mqtt_port);
    mqttClient.setCallback(mqttCallback);
}

void checkAndConnect(void) {
    // WiFi连接处理
    while(WiFi.status() != WL_CONNECTED){
        if(++retry_count > 30){
            ESP.restart();
        }
        sta.wifi_connected = false;
        sta.server_connected = false;
        vTaskDelay(500);
    }
    sta.wifi_connected = true;
    retry_count = 0;

    // MQTT连接处理
    while (!mqttClient.connected()) {
        if (mqttClient.connect(deviceId.c_str(), mqtt_user, mqtt_pass)) {
            sta.server_connected = true;
            registerTopics(); // 注册订阅主题
        } else {
            vTaskDelay(5000);
        }
    }

    sta.server_connected = true;
}

void registerTopics() {
    // 遍历所有主题配置进行订阅
    for (auto &config : topic_configs) {
        if (config.callback != nullptr) { // 有回调的为订阅主题
            mqttClient.subscribe(config.topic);
            Serial.printf("已订阅主题: %s\n", config.topic);
        }
    }
}

void mqttCallback(char* topic, byte* payload, unsigned int length) {
    // 路由回调到对应的处理函数
    for (auto &config : topic_configs) {
        if (strcmp(topic, config.topic) == 0 && config.callback != nullptr) {
            config.callback(topic, payload, length);
            return;
        }
    }
    Serial.printf("未处理的主题: %s\n", topic);
}

// 示例订阅回调函数
void controlCallback(char* topic, byte* payload, unsigned int length) {
    // 创建JSON文档（根据实际数据大小调整容量）
    JsonDocument doc;
    
    // 反序列化JSON数据
    DeserializationError error = deserializeJson(doc, payload, length);
    
    if (error) {
        Serial.printf("JSON解析失败: %s\n", error.c_str());
        return;
    }

    // 提取字段值（示例字段）
    const char* command = doc["command"] | "default"; // 带默认值
    int value = doc["value"] | 0;                     // 带默认值
    bool isActive = doc["active"];                    // 不带默认值
    
    // 类型安全获取（推荐方式）
    if(doc.containsKey("temperature")) {
        float temperature = doc["temperature"].as<float>();
    }

    // 使用解析后的数据
    Serial.printf("命令: %s, 值: %d, 激活状态: %s\n", 
                 command, value, isActive ? "true" : "false");
}

// 发布消息函数示例
void publishMessage(const char* topic, const char* message) {
    if (mqttClient.connected()) {
        mqttClient.publish(topic, message);
    }
}

// 专用主题发布函数
void publishDeviceStatus(bool online, float voltage) {
    publishMessage(topic_configs[0].topic, 
                  JsonAPI::deviceStatus(online, voltage).c_str());
}
